﻿using System;
using Quest.PowerGUI;
using Quest.PowerGUI.Engine.Shell;
using Quest.PowerGUI.ScriptEditor;
using Quest.PowerGUI.ScriptEditor.Shared;
using Quest.PowerGUI.ScriptEditor.Shared.Debugger;

namespace PowerGuiVsx.Core.DebugEngine
{
    public class ScriptDebugger 
    {
        public event Action<string> DocumentChanged;

        public void OnDocumentChanged(string fileName)
        {
            if (DocumentChanged != null)
            {
                DocumentChanged(fileName);
            }
        }

        public ScriptDebugger(DebuggerManager manager, IShellPart shellPart)
        {
            DebuggerManager = manager;
            Shell = shellPart;
        }

        public IShellPart Shell { get; set; }

        public DebuggerManager DebuggerManager { get; private set; }

        private IShellPart GetShell(RunScriptMode mode)
        {
            return DebuggerManager.GetCurrentMonadShell(mode, () => Shell.GetModulesSnapins(false, new ScriptParameters()));
        }

        public void Go(RunScriptMode mode, string parameters = null)
        {
            IShellPart shell = GetShell(mode);
            if (shell != null)
            {
                DebuggerManager.UpdateBreakponitsOnSaveFile(DebuggerManager.CurrentPSControl);
                DebuggerSettings.BreakExecuting = false;

                //DebuggerManager.CurrentPSControl.ReadOnly = true;
                DebuggerManager.CurrentPSControl.Refresh();

                var text = DebuggerManager.CurrentPSControl.SelectedView.SelectedText;
                var fileName = DebuggerManager.CurrentPSControl.Filename;

                var p = new ScriptProvider {Script = text, ScriptName = fileName, ScriptParams = parameters};

                DebuggerManager.Execute(p, mode);
            }
        }
    }
}